<template>
  <div class="auth-wrap">
    <!-- 背景层：渐变+网格+流光粒子 + 动态粒子网络Canvas -->
    <div class="bg">
      <canvas ref="bgCanvas" class="bg-canvas"></canvas>
      <div class="orb orb1"></div>
      <div class="orb orb2"></div>
      <div class="orb orb3"></div>
      <div class="grid"></div>
    </div>

    <div class="content">
      <!-- 品牌侧 -->
      <section class="brand">
        <img :src="logoSrc" alt="Logo" class="brand-logo" />
        <h1>创建账户</h1>
        <p class="subtitle">注册即可体验智能协同的企业资源规划平台</p>
      </section>

      <!-- 注册面板 -->
      <section class="panel" @mousemove="onMouseMove" @mouseleave="onMouseLeave" :style="panelStyle">
        <div class="panel-header">
          <h2>欢迎加入</h2>
          <p>填写信息以创建你的 ERP 账户</p>
        </div>

        <el-form ref="regFormRef" :model="regForm" :rules="regRules" class="reg-form" @submit.prevent="handleRegister">
          <el-form-item prop="username">
            <el-input v-model="regForm.username" placeholder="用户名" size="large" prefix-icon="User" />
          </el-form-item>

          <el-form-item prop="email">
            <el-input v-model="regForm.email" placeholder="邮箱地址" size="large" prefix-icon="Message" />
          </el-form-item>

          <el-form-item prop="phone">
            <el-input v-model="regForm.phone" placeholder="手机号（可选）" size="large" prefix-icon="Phone" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="regForm.password" type="password" placeholder="设置密码" size="large" prefix-icon="Lock" show-password />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input v-model="regForm.confirmPassword" type="password" placeholder="确认密码" size="large" prefix-icon="Lock" show-password />
          </el-form-item>

          <el-form-item>
            <div class="reg-options">
              <el-checkbox v-model="regForm.agree">我已阅读并同意《服务条款》</el-checkbox>
              <el-link type="primary" :underline="false" @click="goLogin">已有账号？去登录</el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="large" class="reg-btn gradient" :loading="loading" @click="handleRegister">
              {{ loading ? '提交中...' : '注册' }}
            </el-button>
          </el-form-item>
        </el-form>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api/index.js'

const router = useRouter()

const regFormRef = ref()
const loading = ref(false)

const regForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  agree: true
})

const validateConfirm = (rule, value, callback) => {
  if (value !== regForm.password) callback(new Error('两次输入的密码不一致'))
  else callback()
}

const regRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^\d{11}$/, message: '手机号需为11位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirm, trigger: 'blur' }
  ]
}

// 面板交互动效
const panelStyle = ref({ transform: 'rotateX(0deg) rotateY(0deg)' })
const onMouseMove = (e) => {
  const b = e.currentTarget.getBoundingClientRect()
  const rx = ((e.clientY - b.top) / b.height - 0.5) * -6
  const ry = ((e.clientX - b.left) / b.width - 0.5) * 6
  panelStyle.value = { transform: `rotateX(${rx}deg) rotateY(${ry}deg)` }
}
const onMouseLeave = () => { panelStyle.value = { transform: 'rotateX(0deg) rotateY(0deg)' } }

// 背景 Logo
const logoSrc = '/favicon.ico'

// 动态背景 Canvas 粒子网络（与登录页一致）
const bgCanvas = ref(null)
let ctx = null
let particles = []
let rafId = null
const mouse = { x: null, y: null }
const initParticles = (w, h, density = 0.00012) => {
  const count = Math.max(60, Math.floor(w * h * density))
  particles = Array.from({ length: count }, () => ({
    x: Math.random() * w,
    y: Math.random() * h,
    vx: (Math.random() - 0.5) * 0.6,
    vy: (Math.random() - 0.5) * 0.6,
    r: 1.1 + Math.random() * 1.2
  }))
}
const resizeCanvas = () => {
  if (!bgCanvas.value) return
  const w = bgCanvas.value.width = window.innerWidth
  const h = bgCanvas.value.height = window.innerHeight
  initParticles(w, h)
}
const draw = () => {
  if (!ctx) return
  const w = bgCanvas.value.width
  const h = bgCanvas.value.height
  ctx.clearRect(0, 0, w, h)
  for (const p of particles) {
    p.x += p.vx; p.y += p.vy
    if (p.x < 0 || p.x > w) p.vx *= -1
    if (p.y < 0 || p.y > h) p.vy *= -1
    if (mouse.x != null && mouse.y != null) {
      const dx = mouse.x - p.x, dy = mouse.y - p.y
      const dist = Math.sqrt(dx*dx + dy*dy)
      if (dist < 120) { p.vx += dx / dist * 0.02; p.vy += dy / dist * 0.02 }
    }
    ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.55)'; ctx.fill()
  }
  for (let i = 0; i < particles.length; i++) {
    for (let j = i + 1; j < particles.length; j++) {
      const a = particles[i], b = particles[j]
      const dx = a.x - b.x, dy = a.y - b.y
      const d2 = dx*dx + dy*dy
      if (d2 < 110*110) {
        const alpha = 1 - (Math.sqrt(d2) / 110)
        ctx.strokeStyle = `rgba(175, 220, 255, ${alpha * 0.45})`
        ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke()
      }
    }
  }
  rafId = requestAnimationFrame(draw)
}
onMounted(() => {
  if (bgCanvas.value) {
    ctx = bgCanvas.value.getContext('2d')
    resizeCanvas(); draw()
    window.addEventListener('resize', resizeCanvas)
    window.addEventListener('mousemove', (e) => { mouse.x = e.clientX; mouse.y = e.clientY })
    window.addEventListener('mouseleave', () => { mouse.x = null; mouse.y = null })
  }
})
onUnmounted(() => { window.removeEventListener('resize', resizeCanvas); if (rafId) cancelAnimationFrame(rafId) })

// 注册提交
const handleRegister = async () => {
  if (!regFormRef.value) return
  try {
    await regFormRef.value.validate()
    if (!regForm.agree) {
      ElMessage.warning('请先阅读并同意服务条款');
      return
    }
    loading.value = true
    const { data } = await userAPI.createUser({
      username: regForm.username,
      email: regForm.email,
      phone: regForm.phone,
      // 密码仅用于演示，真实环境请在后端进行加密与存储
      password: regForm.password,
      role: 'User',
      status: '启用'
    })
    ElMessage.success(`注册成功，欢迎你：${data.username}`)
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const goLogin = () => router.push('/login')
</script>

<style scoped>
.auth-wrap { position: relative; min-height: 100vh; display: flex; align-items: center; justify-content: center; overflow: hidden;
  background: radial-gradient(1200px 600px at 10% 10%, rgba(92, 30, 243, 0.2), transparent),
              radial-gradient(1000px 500px at 90% 90%, rgba(12, 183, 255, 0.18), transparent),
              linear-gradient(135deg, #0f1029 0%, #1a1b3b 50%, #0b0c1a 100%);
}
.bg { position: absolute; inset: 0; }
.bg-canvas { position: absolute; inset: 0; }
.orb { position: absolute; width: 500px; height: 500px; border-radius: 50%; filter: blur(60px); opacity: 0.35; animation: float 12s ease-in-out infinite; }
.orb1 { top: -80px; left: -80px; background: radial-gradient(circle, #6035ff, #2a1a7f); }
.orb2 { bottom: -120px; right: -120px; background: radial-gradient(circle, #00d4ff, #005b96); animation-delay: 2s; }
.orb3 { top: 40%; left: 60%; background: radial-gradient(circle, #ff4fd8, #6b1a55); animation-delay: 4s; }
@keyframes float { 0%,100% { transform: translateY(0) translateX(0) } 50% { transform: translateY(-20px) translateX(15px) } }
.grid::before { content: ''; position: absolute; inset: 0; background-image:
  linear-gradient(rgba(255,255,255,0.06) 1px, transparent 1px),
  linear-gradient(90deg, rgba(255,255,255,0.06) 1px, transparent 1px);
  background-size: 40px 40px; mask-image: radial-gradient(circle at 50% 50%, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.5) 40%, rgba(0,0,0,0) 70%);
}
.content { position: relative; z-index: 2; display: grid; grid-template-columns: 1.2fr 1fr; gap: 48px; align-items: center; padding: 40px; width: min(1100px, 92vw); }
.brand { color: #e5e7ff; padding: 24px 16px; }
.brand-logo { width: 72px; height: 72px; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.35); }
.brand h1 { margin: 16px 0 8px; font-size: 36px; font-weight: 700; letter-spacing: 1px; }
.subtitle { margin: 0; color: #b7b9d6; font-size: 14px; }
.panel { position: relative; perspective: 800px; transform-style: preserve-3d; background: rgba(255, 255, 255, 0.08); border: 1px solid rgba(255, 255, 255, 0.22);
  backdrop-filter: blur(16px) saturate(120%); border-radius: 18px; box-shadow: 0 20px 60px rgba(0,0,0,0.45); padding: 28px 28px 22px; }
.panel-header h2 { margin: 0 0 6px; font-size: 22px; color: #fff; font-weight: 700; }
.panel-header p { margin: 0 0 18px; color: #cfd1e6; font-size: 13px; }
.reg-form { margin-top: 6px; }
.reg-options { display: flex; justify-content: space-between; align-items: center; width: 100%; }
.reg-btn { width: 100%; height: 46px; font-size: 16px; font-weight: 700; }
.gradient { background-image: linear-gradient(90deg, #6a5cfe 0%, #00d4ff 100%); border: none; }
.gradient:hover { filter: brightness(1.06); }
:deep(.el-input__wrapper) { background-color: rgba(255,255,255,0.12); box-shadow: none; border-color: transparent; }
:deep(.el-input__inner) { color: #fff; }
:deep(.el-form-item__label) { color: #cfd1e6; }
:deep(.el-checkbox__label) { color: #cfd1e6; }
@media (max-width: 920px) { .content { grid-template-columns: 1fr; gap: 24px; padding: 28px; } .brand { text-align: center; } }
</style>